package com.ntd.study.base.thread;

import cn.hutool.core.lang.Console;
import ntd.util.UtilThread;

/**
 * 生产者-消费者模式
 */
public class TestProductorAndConsumer {
    private static Clerk clerk = new Clerk();

    static class Productor implements Runnable { // 生产者
        @Override
        public void run() {
            for (int i = 0; i < 15; i++) {
                UtilThread.sleep(200);
                clerk.get();
            }
        }
    }

    static class Consumer implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 15; i++) {
                clerk.sale();
            }
        }
    }

    public static void main(String[] args) {
        new Thread(new Consumer()).start();
        new Thread(new Productor()).start();
        new Thread(new Consumer()).start();
        new Thread(new Productor()).start();
    }
}

class Clerk { // 店员
    private int product = 0;

    public synchronized void get() {
        while (product >= 1) {
            Console.log("产品已满");
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Console.log("生产" + ++product);
        this.notifyAll();
    }

    public synchronized void sale() {
        while (product < 1) {
            Console.log("缺货");
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Console.log("消费" + --product);
        this.notifyAll();
    }
}

